﻿using System.Linq;
using élénkPróbája.assets;

namespace élénkPróbája.validators
{
    public class CreditCardValidator : PropertyValidator
    {
        public CreditCardValidator() : base(() => Messages.CreditCardError) {
        }

        protected override bool IsValid(PropertyValidatorContext context)
        {
            var value = context.PropertyValue as string;

            if (value == null)
            {
                return true;
            }

            value = value.Replace("-", "").Replace(" ", "");

            int checksum = 0;
            bool evenDigit = false;
            foreach (char digit in value.ToCharArray().Reverse())
            {
                if (!char.IsDigit(digit))
                {
                    return false;
                }

                int digitValue = (digit - '0') * (evenDigit ? 2 : 1);
                evenDigit = !evenDigit;

                while (digitValue > 0)
                {
                    checksum += digitValue % 10;
                    digitValue /= 10;
                }
            }

            return (checksum % 10) == 0;
        }
    }
}